package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.ProductConstant;
import com.atguigu.common.es.SkuEsModel;
import com.atguigu.common.es.SkuHasStockVo;
import com.atguigu.common.to.SkuReductionTo;
import com.atguigu.common.to.SpuBoundTo;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.product.dao.AttrDao;
import com.atguigu.gulimall.product.dao.SpuInfoDao;
import com.atguigu.gulimall.product.entity.*;
import com.atguigu.gulimall.product.feign.CouponFeignService;
import com.atguigu.gulimall.product.feign.SearchFeignService;
import com.atguigu.gulimall.product.feign.WareFeignService;
import com.atguigu.gulimall.product.service.*;
import com.atguigu.gulimall.product.vo.spuinfovo.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import org.springframework.transaction.annotation.Transactional;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    SearchFeignService searchFeignService;

    @Autowired
    WareFeignService wareFeignService;

    @Autowired
    AttrDao attrDao;

    @Autowired
    AttrService attrService;

    @Autowired
    CategoryService categoryService;

    @Autowired
    BrandService brandService;

    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    SkuImagesService skuImagesService;

    @Autowired
    SkuInfoService skuInfoService;

    @Autowired
    ProductAttrValueService productAttrValueService;

    @Autowired
    SpuImagesService spuImagesService;

    @Autowired
    SpuInfoDescService spuInfoDescService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * SpuSaveVo字段与数据库表关系：
     * 数据库 gulimall_pms
     * 1. 保存spu基本信息 `pms_spu_info`
     * 2. 保存spu描述图片 `pms_spu_info_desc`     List<String> decript;
     * 3. 保存spu图片集 `pms_spu_images`     List<String> images
     * 4. 保存spu规格参数 `pms_product_attr_value`   List<BaseAttrs> baseAttrs;
     * 5. 保存spu对应的sku信息 `pms_sku_info`  List<Skus> skus
     * <p>
     * 数据库 gulimall_sms
     * 6. 保存spu积分信息 `sms_spu_bounds` Bounds bounds;
     * <p>
     * Skus字段与数据库表关系：
     * 5.1 sku图片集 `pms_sku_images`  List<Images> images;
     * 5.2 sku销售属性 `pms_sku_sale_attr_value`  List<Attr> attr;
     * <p>
     * 5.3 保存spu的积分信息-调用gulimall-coupon积分服务
     * 5.4 保存sku的打折、满减信息
     * 数据库 gulimall_sms
     * 打折表`sms_sku_ladder`
     * 满减表`sms_sku_full_reduction`
     * 会员级别价格表`sms_member_price`
     */
    //保存发布的商品
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo spuSaveVo) throws ParseException {

        //1. 保存spu基本信息 `pms_spu_info`
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVo, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.saveBaseSpuInfo(spuInfoEntity);

        //2. 保存spu描述图片 `pms_spu_info_desc`  List<String> decript;
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        List<String> decripts = spuSaveVo.getDecript();
        //上面id自增会回填，可以直接查
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        //使用逗号拼接list集合的元素 https://xxx1.jpg,https://xxx2.jpg
        spuInfoDescEntity.setDecript(String.join(",", decripts));
        spuInfoDescService.saveSpuInfoDesc(spuInfoDescEntity);

        //3. 保存spu图片集 `pms_spu_images`     List<String> images
        spuImagesService.saveSpuImages(spuInfoEntity.getId(), spuSaveVo.getImages());

        //4. 保存spu规格参数 `pms_product_attr_value`   List<BaseAttrs> baseAttrs;
        productAttrValueService.saveProductAttrValue(spuInfoEntity.getId(), spuSaveVo.getBaseAttrs());

        //5.3 保存spu的积分信息-调用gulimall-coupon积分服务
        Bounds bounds = spuSaveVo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds,spuBoundTo);
        spuBoundTo.setSpuId(spuInfoEntity.getId());
        R r = couponFeignService.saveSpuBounds(spuBoundTo);
        if (r.getCode() != 0){
            log.error("远程保存spu的积分信息失败");
        }

        //5. 保存spu对应的sku信息 `pms_sku_info`  List<Skus> skus
        //Skus字段与数据库表关系：
        List<Skus> skus = spuSaveVo.getSkus();
        if (skus != null && skus.size() > 0) {
            //这里为什么不使用stream，因为skus类使用流时不方便调用其他对象？
            skus.forEach(sku -> {
                //这里先单独查询出的结果是用于存入SkuInfoEntity，后面存入SkuImagesEntity时需要存入sku_id，要在存入SkuInfoEntity之后进行，所以分开查询images
                //存图片信息需要sku_id ，sku_id需要存了SkuInfoEntity才会有
                String img = "";
                for (Images image : sku.getImages()) {
                    //默认图[0 - 不是默认图，1 - 是默认图]
                    if (image.getDefaultImg() == 1) {
                        img = image.getImgUrl();
                    }
                }
//                private String skuName;
//                private BigDecimal price;
//                private String skuTitle;
//                private String skuSubtitle;
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(sku, skuInfoEntity);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setCatalogId(spuSaveVo.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setBrandId(spuSaveVo.getBrandId());
                //只存默认图
                skuInfoEntity.setSkuDefaultImg(img);
                skuInfoService.saveSkuIfo(skuInfoEntity);

                //5.1 sku图片集 `pms_sku_images`  List<Images> images;
                //TODO 图片信息没有数据的不保存
                List<SkuImagesEntity> imagesEntities = sku.getImages().stream().map(itemImg -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    //拿到回显id
                    skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                    skuImagesEntity.setDefaultImg(itemImg.getDefaultImg());
                    skuImagesEntity.setImgUrl(itemImg.getImgUrl());
                    return skuImagesEntity;
                }).filter(entity->{
                    //true返回不为空的图片，false不返回
                    return StringUtils.isNotEmpty(entity.getImgUrl());
                }).collect(Collectors.toList());
//                skuImagesService.saveBatchSkuImages(imagesEntities);
                skuImagesService.saveBatch(imagesEntities);

                //5.2 sku销售属性 `pms_sku_sale_attr_value`  List<Attr> attr;
                List<Attr> attrs = sku.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attrs.stream().map(attr -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);

                //5.4 保存sku的打折、满减信息,数据库 gulimall_sms,打折表`sms_sku_ladder`,满减表`sms_sku_full_reduction`,会员级别价格表`sms_member_price`
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(sku,skuReductionTo);
                skuReductionTo.setSkuId(skuInfoEntity.getSkuId());
                //如果满几件和满多少都不存在则不用调用远程服务
                if (skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(BigDecimal.ZERO) == 1){
                    R r1 = couponFeignService.saveSkuReduction(skuReductionTo);
                    if (r1.getCode() != 0){
                        log.error("远程保存sku的打折、满减信息失败");
                    }
                }


            });

        }
    }




    @Override
    public void saveBaseSpuInfo(SpuInfoEntity spuInfoEntity) {
        this.save(spuInfoEntity);
    }

    /**
     * status: 1
     * key:
     * brandId: 0
     * catelogId: 0
     */
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> spuInfoEntityQueryWrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        //and(id=? or name like ?)
        if (StringUtils.isNotEmpty(key)){
            spuInfoEntityQueryWrapper.and((wrapper)->{
                wrapper.eq("id",key).or().like("spu_name",key);
            });
        }
        //这里直接转String条件构造器也可以查
        String brandId = (String) params.get("brandId");
        spuInfoEntityQueryWrapper.eq(!StringUtils.isEmpty(brandId)&&!"0".equalsIgnoreCase(brandId),"brand_id",brandId);
        String catelogId = (String) params.get("catelogId");
        spuInfoEntityQueryWrapper.eq(!StringUtils.isEmpty(catelogId)&&"0".equalsIgnoreCase(catelogId),"catalog_id",catelogId);
        String status = (String) params.get("status");
        spuInfoEntityQueryWrapper.eq(StringUtils.isNotEmpty(status),"publish_status",status);

        IPage<SpuInfoEntity> page =
                this.page(new Query<SpuInfoEntity>().getPage(params), spuInfoEntityQueryWrapper);
        return new PageUtils(page);
    }





    //商品上架:上架是将后台的商品放在 es 中可以提供检索和查询功能
    @Override
    public void up(Long spuId) {
        //根据spuid查出sku集合
        List<SkuInfoEntity> skuInfoEntities = skuInfoService.querySkuBySpuId(spuId);

        //TODO 4.查询当前sku规格属性，并判断是否可以检索 search_type
        /**
         * 根据Spuid查表`pms_product_attr_value`，取出attr_id,查这些属性idattr_id的属性
         * 筛选出符合检索的search_type=1的attr
         * 然后拿到 attr的attr_id=product_attr_value的attr_id 的数据插入SkuEsModel.Attrs
         */
        List<ProductAttrValueEntity> productAttrValueList = productAttrValueService.baseAttrlistforspu(spuId);
        //获取attrIds
        List<Long> attrIds = productAttrValueList.stream().map(productAttrValue -> {
            Long attrId = productAttrValue.getAttrId();
            return attrId;
        }).collect(Collectors.toList());

        //筛选出search_type=1的attr
        List<AttrEntity> list = attrDao.selectBatchIds(attrIds);
        List<Long> productAttrIds = list.stream().filter(attr -> {
            return attr.getSearchType() == 1;
        }).map(attrEntity -> {
            return attrEntity.getAttrId();
        }).collect(Collectors.toList());

        HashSet<Long> idSet = new HashSet<>(productAttrIds);

        //拿到search_type=1的product_attr_value数据
        List<SkuEsModel.Attrs> esAttrList = productAttrValueList.stream().filter(item -> {
            //筛选
            return idSet.contains(item.getAttrId());
        }).map(attr -> {
            //给SkuEsModel.Attrs赋值
            SkuEsModel.Attrs esAttr = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(attr, esAttr);
            return esAttr;
        }).collect(Collectors.toList());

        //TODO 1.发送远程调用 库存系统查询是否有库存
        //注意调用时，传的参数有序列化问题
        List<Long> skuIds = skuInfoEntities.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        Map<Long, Boolean> booleanMap = null;
        try {
            R<List<SkuHasStockVo>> r = wareFeignService.getSkuHasStock(skuIds);
            Integer code = r.getCode();
            List<SkuHasStockVo> data = r.getData(new TypeReference<List<SkuHasStockVo>>(){});
            booleanMap = data.stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.getHasStock()));
        } catch (Exception e) {
            log.error("库存服务查询异常:原因{}",e);
        }

        //循环查数据库？
        Map<Long, Boolean> finalBooleanMap = booleanMap;
        List<SkuEsModel> collect = skuInfoEntities.stream().map(sku -> {
            SkuEsModel esModel = new SkuEsModel();
            BeanUtils.copyProperties(sku, esModel);
            esModel.setSkuImg(sku.getSkuDefaultImg());
            esModel.setSkuPrice(sku.getPrice());
            esModel.setAttrs(esAttrList);

            //拿到远程查出的库存状态
            if (finalBooleanMap == null){
                //为null表示调用库存服务失败，直接给一个默认库存
                //有库存true  无库存false，默认有数据为true
                esModel.setHasStock(true);
            }else {
                //调用库存服务成功，直接设置库存状态
                esModel.setHasStock(finalBooleanMap.get(sku.getSkuId()));
            }

            //TODO 2.热度评分 0?
            esModel.setHotScore(0L);

            //TODO 3.查询品牌和分类的名字信息
            BrandEntity brand = brandService.getById(esModel.getBrandId());
            esModel.setBrandName(brand.getName());
            esModel.setBrandImg(brand.getLogo());

            CategoryEntity category = categoryService.getById(esModel.getCatalogId());
            esModel.setCatalogName(category.getName());

            return esModel;
        }).collect(Collectors.toList());

        //TODO 5.es服务保存数据
        R r = searchFeignService.productStatusUp(collect);
        if (r.getCode() == 0){
            //TODO 6.修改商品上架状态 上架状态[0 - 下架，1 - 上架]
            this.baseMapper.updataSpuStatus(spuId, ProductConstant.StatusEnum.SUP_UP.getCode());
        }else {
            //远程调用失败
            //TODO 7.重复调用？接口幂等性：重试机制？
        }


    }

}